package com.wanshi.utils;

import com.wanshi.exception.MyException;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;

@SuppressWarnings("all")
public class DatiOutTask2 implements Callable{

    private String name;
    private String method;
    private Object[] objs;
    private String path;


    public DatiOutTask2(String name, String method, String path, Object[] objs){
        this.name = name;
        this.method = method;
        this.path = path;
        this.objs =objs;
    };

    @Override
    public String call() throws Exception {
        //3 反射调方法
        Class<?> c = Class.forName(name);
        // 反射类的方法：
        Method[] ms = c.getMethods();
        for (int i = 0; i < ms.length; i++) {
            String methodName = ms[i].getName();
            if(methodName.equals(method)){
                return getString(c, ms[i], objs);

            }
        }
        return null;
    }



    private String getString(Class<?> c, Method m, Object[] obj) {
        System.out.println(path);
        System.out.println(name);

        File fileTxt = new File(path, name + ".txt");
        PrintStream ps = null;
        try{
            fileTxt.createNewFile();

            PrintStream out = System.out;
            ps = new PrintStream(fileTxt.getAbsolutePath());
            System.setOut(ps);
            m.invoke(c.getDeclaredConstructor().newInstance(), obj);
            System.setOut(out);

            FileReader fr = new FileReader(fileTxt.getAbsoluteFile());
            String result =  readContent(fr);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException("写入失败!");
        }finally {
            if(ps != null){
                ps.close();
            }
            if(fileTxt!=null && fileTxt.exists()){
                fileTxt.delete();
            }
        }
    }

    public String readContent(FileReader fr) {
        char[] cs = new char[1024];
        int len;
        StringBuffer buffer = new StringBuffer();
        try{
            while( (len = fr.read(cs)) != -1){
                buffer.append(cs,0,len);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            if(fr != null){
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer.toString();
    }

}
